#include "viml/garbage_collector.h"
#include "viml/object.h"
#include "viml/value.h"
#include <iostream>
#include <algorithm>
#include <cstring>

namespace viml {

GarbageCollector::GarbageCollector() : incremental_phase_(IncrementalPhase::IDLE), is_collecting_(false) {
    // 初始化分代配置
    configs_[static_cast<size_t>(Generation::YOUNG)] = {1024 * 64, 3, 10000};
    configs_[static_cast<size_t>(Generation::OLD_0)] = {1024 * 256, 8, 5000};
    configs_[static_cast<size_t>(Generation::OLD_1)] = {1024 * 512, 16, 2000};
    configs_[static_cast<size_t>(Generation::OLD_2)] = {1024 * 1024, 32, 1000};

    // 预分配对象存储空间
    for (size_t i = 0; i < GENERATION_COUNT; ++i) {
        generation_objects_[i].reserve(configs_[i].capacity);
    }
}


void GarbageCollector::set_root_set(GCRootSet* root_set) {
    root_set_ = root_set;
}

void GarbageCollector::add_object(Object* obj) {
    if (!obj || !obj->is_valid_object()) {
        return;
    }

    std::lock_guard<std::mutex> lock(gc_mutex_);
    if (!is_collecting_) {
        // 将对象添加到年轻代
        move_to_generation(obj, Generation::YOUNG, Generation::YOUNG);
        total_allocations_++;

        // 检查是否需要启动增量收集
        if (needs_incremental_collection()) {
            start_incremental_collection();
        }
    }
}

GarbageCollector::CollectionResult GarbageCollector::collect() {
    std::lock_guard<std::mutex> lock(gc_mutex_);

    if (is_collecting_ || !is_enabled_) {
        CollectionResult result;
        result.collection_time_ms = 0.0;
        return result;
    }

    is_collecting_ = true;
    auto start_time = std::chrono::high_resolution_clock::now();

    std::cout << "开始垃圾回收..." << std::endl;

    // 第一步：标记阶段
    mark_phase();

    // 第二步：清除阶段
    sweep_phase();

    // 第三步：对象晋升和平衡
    perform_promotions();
    balance_generations();

    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);

    CollectionResult result;
    result.collection_time_ms = duration.count();
    result.objects_collected = collection_count_;
    result.bytes_collected = result.objects_collected * estimate_average_object_size();

    std::cout << "垃圾回收完成：" << std::endl;
    std::cout << "  收集对象数: " << result.objects_collected << std::endl;
    std::cout << "  收集时间: " << result.collection_time_ms << "ms" << std::endl;
    std::cout << "  年轻代收集: " << result.young_gen_collected << std::endl;
    std::cout << "  老年代收集: " << result.old_gen_collected << std::endl;

    // 更新统计信息
    total_collections_++;
    total_collection_time_ms_ += result.collection_time_ms;
    last_collection_time_ = end_time;

    is_collecting_ = false;
    collection_count_ = 0;

    print_generation_stats();
    return result;
}

GarbageCollector::Stats GarbageCollector::get_stats() const {
    std::lock_guard<std::mutex> lock(gc_mutex_);

    Stats stats;
    stats.total_objects = 0;
    for (size_t i = 0; i < GENERATION_COUNT; ++i) {
        stats.total_objects += generation_objects_[i].size();
    }

    stats.young_gen_objects = generation_objects_[static_cast<size_t>(Generation::YOUNG)].size();
    stats.old_gen_0_objects = generation_objects_[static_cast<size_t>(Generation::OLD_0)].size();
    stats.old_gen_1_objects = generation_objects_[static_cast<size_t>(Generation::OLD_1)].size();
    stats.old_gen_2_objects = generation_objects_[static_cast<size_t>(Generation::OLD_2)].size();
    stats.total_bytes_allocated = total_allocations_ * estimate_average_object_size();
    stats.total_bytes_freed = collection_count_ * estimate_average_object_size();
    stats.total_collections = total_collections_;
    stats.average_collection_time_ms = total_collections_ > 0 ?
                                     total_collection_time_ms_ / total_collections_ : 0.0;
    stats.collection_frequency = 0.0; // 可以基于时间间隔计算

    // 增量收集统计
    stats.incremental_collections = incremental_collections_;
    stats.incremental_time_ms = incremental_time_ms_;
    stats.incremental_marked_objects = incremental_marked_objects_;
    stats.incremental_swept_objects = incremental_swept_objects_;
    stats.incremental_efficiency = (incremental_time_ms_ > 0.0) ?
                                   (incremental_marked_objects_ + incremental_swept_objects_) / incremental_time_ms_ : 0.0;

    return stats;
}

void GarbageCollector::reset_stats() {
    std::lock_guard<std::mutex> lock(gc_mutex_);
    total_allocations_ = 0;
    total_collections_ = 0;
    collection_count_ = 0;
    total_collection_time_ms_ = 0.0;
    last_collection_time_ = std::chrono::high_resolution_clock::now();
}

void GarbageCollector::set_enabled(bool enabled) {
    is_enabled_ = enabled;
    (void)enabled; // 避免未使用参数警告
}

bool GarbageCollector::is_enabled() const {
    return is_enabled_;
}

void GarbageCollector::mark_phase() {
    if (!root_set_) {
        std::cout << "警告：未设置根集" << std::endl;
        return;
    }

    std::cout << "标记阶段开始..." << std::endl;

    // 清除所有标记
    for (size_t i = 0; i < GENERATION_COUNT; ++i) {
        for (auto& obj : generation_objects_[i]) {
            if (obj) {
                obj->unmark();
            }
        }
    }

    // 从根对象开始标记可达对象
    root_set_->lock();
    auto roots = root_set_->get_roots();
    for (Object* root : roots) {
        if (root) {
            mark_object(root);
        }
    }
    root_set_->unlock();

    std::cout << "标记阶段完成，标记了根对象数: " << roots.size() << std::endl;
}

void GarbageCollector::mark_object(Object* obj) {
    if (!obj || !obj->is_valid_object() || obj->is_marked()) {
        return;
    }

    obj->mark();

    // 递归标记对象引用的其他对象
    // 这里需要根据对象类型进行特定的标记逻辑
    // 由于复杂性，这里提供一个简化的实现

    // 示例：对于列表对象，标记所有元素
    if (obj->is_list()) {
        auto list_obj = static_cast<ListObject*>(obj);
        for (size_t i = 0; i < list_obj->size(); ++i) {
            Value element = list_obj->get(i);
            mark_value(element);
        }
    }
    // 对于字典对象，标记键和值
    else if (obj->is_dict()) {
        // 简化处理，暂时不标记具体键值
        // TODO: 实现完整的字典标记
    }
}

void GarbageCollector::mark_value(const Value& value) {
    // 暂时简化实现，不处理复杂类型的标记
    // TODO: 实现完整的Value到Object的转换和标记
    (void)value; // 避免未使用参数警告
}

void GarbageCollector::mark_closure(const Closure* closure) {
    // 暂时简化实现，不处理闭包标记
    // TODO: 实现完整的闭包标记
    (void)closure; // 避免未使用参数警告
}

void GarbageCollector::sweep_phase() {
    std::cout << "清除阶段开始..." << std::endl;

    size_t collected_per_gen[GENERATION_COUNT] = {0};
    size_t total_collected = 0;

    // 从年轻代开始清除
    for (size_t gen = 0; gen < GENERATION_COUNT; ++gen) {
        std::cout << "  清除分代 " << generation_to_char(static_cast<Generation>(gen)) << std::endl;

        for (Object* obj : generation_objects_[gen]) {
            // 跳过已被转发的对象
            if (obj && obj->is_forwarded()) {
                continue;
            }

            // 未标记的对象需要被回收
            if (obj && !obj->is_marked()) {
                // 回收对象
                finalize_object(obj);
                total_collected++;
                collection_count_++;
                collected_per_gen[gen]++;
            }
        }

        std::cout << "    从分代 " << generation_to_char(static_cast<Generation>(gen))
                  << " 回收了 " << collected_per_gen[gen] << " 个对象" << std::endl;
    }

    std::cout << "清除阶段完成，总共回收了 " << total_collected << " 个对象" << std::endl;

    // 清除已转发对象（清理转发指针）
    for (size_t gen = 0; gen < GENERATION_COUNT; ++gen) {
        auto& gen_objects = generation_objects_[gen];
        for (auto& obj : gen_objects) {
            if (obj && obj->is_forwarded()) {
                // 重置转发标记
                obj->set_forwarded(false);
            }
        }
    }
}


void GarbageCollector::balance_generations() {
    std::cout << "分代平衡阶段..." << std::endl;

    // 简化的分代平衡逻辑
    // 确保没有分代超出容量限制

    for (size_t i = 0; i < GENERATION_COUNT; ++i) {
        auto& gen = generation_objects_[i];
        auto& config = configs_[i];

        if (gen.size() > config.max_objects) {
            std::cout << "    分代 " << generation_to_char(static_cast<Generation>(i))
                      << " 超出容量 (" << gen.size() << " > " << config.max_objects
                      << ")，触发清理" << std::endl;
            cleanup_generation(static_cast<Generation>(i));
        }
    }
}

void GarbageCollector::cleanup_generation(Generation gen) {
    auto& gen_objects = generation_objects_[static_cast<size_t>(gen)];

    for (Object* obj : gen_objects) {
        if (obj) {
            finalize_object(obj);
        }
    }

    gen_objects.clear();
}

void GarbageCollector::finalize_object(Object* obj) {
    if (!obj) return;

    // 确保对象有正确的析构函数调用
    // 这里可以添加对象特定的清理逻辑

    // 调用析构函数（通过引用计数或直接调用）
    // 注意：实际的delete操作应该在sweep_phase中进行
}

size_t GarbageCollector::get_object_size(Object* obj) const {
    if (!obj) return 0;

    // 简化的对象大小估算
    // 实际实现中应该根据对象类型返回真实大小

    if (obj->is_string()) {
        // 字符串对象大小估算
        return 32; // 平均字符串大小
    } else if (obj->is_list()) {
        // 列表对象大小估算
        return 64; // 平均列表大小
    } else if (obj->is_dict()) {
        // 字典对象大小估算
        return 96; // 平均字典大小
    } else {
        return 48; // 其他对象的平均大小
    }
}

double GarbageCollector::estimate_average_object_size() const {
    return 64.0; // 简化：假设平均对象大小为64字节
}

void GarbageCollector::move_to_generation(Object* obj, Generation from_gen, Generation to_gen) {
    remove_from_generation(obj, from_gen);

    auto& target_gen = generation_objects_[static_cast<size_t>(to_gen)];
    target_gen.insert(obj);

    obj->set_generation(static_cast<uint8_t>(to_gen));
}

void GarbageCollector::remove_from_generation(Object* obj, Generation from_gen) {
    auto& source_gen = generation_objects_[static_cast<size_t>(from_gen)];
    source_gen.erase(obj);
}

void GarbageCollector::promote_object(Object* obj, Generation new_generation) {
    obj->set_generation(static_cast<uint8_t>(new_generation));

    auto& target_gen = generation_objects_[static_cast<size_t>(new_generation)];
    target_gen.insert(obj);
}

GarbageCollector::Generation GarbageCollector::get_object_generation(Object* obj) const {
    if (!obj) return Generation::YOUNG;

    uint8_t gen = obj->get_generation();
    if (gen < 10) return Generation::YOUNG;
    else if (gen < 20) return Generation::OLD_0;
    else if (gen < 30) return Generation::OLD_1;
    else return Generation::OLD_2;
}

const char* GarbageCollector::generation_to_char(Generation gen) const {
    static const char* gen_names[] = {"YOUNG", "OLD_0", "OLD_1", "OLD_2"};
    return gen_names[static_cast<size_t>(gen)];
}

void GarbageCollector::print_generation_stats() const {
    std::cout << "=== 分代统计 ===" << std::endl;
    for (size_t i = 0; i < GENERATION_COUNT; ++i) {
        std::cout << "分代 " << generation_to_char(static_cast<Generation>(i)) << ": "
                  << generation_objects_[i].size() << " 个对象, 容量: "
                  << configs_[i].capacity << std::endl;
    }
    std::cout << "=================" << std::endl;
}

void GarbageCollector::lock_gc() {
    gc_mutex_.lock();
}

void GarbageCollector::unlock_gc() {
    gc_mutex_.unlock();
}

// GCManager实现
std::unique_ptr<GarbageCollector> GCManager::instance_;
std::mutex GCManager::instance_mutex_;
GCRootSet* GCManager::global_root_set_ = nullptr;

GarbageCollector& GCManager::get_instance() {
    std::lock_guard<std::mutex> lock(instance_mutex_);
    if (!instance_) {
        instance_ = std::make_unique<GarbageCollector>();
        if (global_root_set_) {
            instance_->set_root_set(global_root_set_);
        }
    }
    return *instance_;
}

void GCManager::set_global_root_set(GCRootSet* root_set) {
    std::lock_guard<std::mutex> lock(instance_mutex_);
    global_root_set_ = root_set;
    if (instance_) {
        instance_->set_root_set(root_set);
    }
}

GarbageCollector::CollectionResult GCManager::collect_garbage() {
    if (instance_) {
        return instance_->collect();
    }
    return GarbageCollector::CollectionResult{};
}

GarbageCollector::Stats GCManager::get_global_stats() {
    if (instance_) {
        return instance_->get_stats();
    }
    return GarbageCollector::Stats{};
}

void GCManager::reset_global_stats() {
    if (instance_) {
        instance_->reset_stats();
    }
}

void GCManager::disable() {
    if (instance_) {
        instance_->set_enabled(false);
    }
}

void GCManager::enable() {
    if (instance_) {
        instance_->set_enabled(true);
    }
}

GarbageCollector::CollectionResult GCManager::incremental_collect() {
    if (instance_) {
        return instance_->incremental_collect();
    }
    return GarbageCollector::CollectionResult{};
}

bool GCManager::needs_incremental_collection() {
    if (instance_) {
        return instance_->needs_incremental_collection();
    }
    return false;
}

GarbageCollector::IncrementalPhase GCManager::get_incremental_phase() {
    if (instance_) {
        return instance_->get_incremental_phase();
    }
    return GarbageCollector::IncrementalPhase::IDLE;
}

// GCRootSet优化方法实现
void GCRootSet::add_root(Object* obj) {
    add_root(obj, RootType::USER);
}

void GCRootSet::add_root(Object* obj, RootType type) {
    if (!obj || !obj->is_valid_object() || locked_) {
        return;
    }

    auto start_time = std::chrono::high_resolution_clock::now();

    // 检查是否已存在
    auto result = root_set_.insert(obj);
    if (result.second) {
        // 新对象，添加到类型映射和列表
        root_types_[obj] = type;
        list_dirty_ = true;
        update_stats(obj, type, true);
    } else {
        // 重复对象，更新类型（如果需要）
        auto it = root_types_.find(obj);
        if (it != root_types_.end() && it->second != type) {
            it->second = type;
        }
        stats_.duplicate_removals++;
    }

    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);

    // 更新平均添加时间
    stats_.avg_add_time_us = (stats_.avg_add_time_us * (stats_.total_roots - 1) + duration.count()) / stats_.total_roots;
}

bool GCRootSet::remove_root(Object* obj) {
    if (!obj || locked_) {
        return false;
    }

    auto it = root_set_.find(obj);
    if (it != root_set_.end()) {
        auto type_it = root_types_.find(obj);
        RootType type = (type_it != root_types_.end()) ? type_it->second : RootType::USER;

        root_set_.erase(it);
        root_types_.erase(type_it);
        list_dirty_ = true;
        update_stats(obj, type, false);
        return true;
    }
    return false;
}

void GCRootSet::add_value_root(const Value& value) {
    add_value_root(value, RootType::USER);
}

void GCRootSet::add_value_root(const Value& value, RootType type) {
    std::vector<Object*> objects;
    if (extract_objects_from_value(value, objects)) {
        for (Object* obj : objects) {
            add_root(obj, type);
        }
    }
}

bool GCRootSet::remove_value_root(const Value& value) {
    std::vector<Object*> objects;
    if (extract_objects_from_value(value, objects)) {
        bool removed_any = false;
        for (Object* obj : objects) {
            if (remove_root(obj)) {
                removed_any = true;
            }
        }
        return removed_any;
    }
    return false;
}

void GCRootSet::add_roots(const std::vector<Object*>& objects) {
    add_roots(objects, RootType::USER);
}

void GCRootSet::add_roots(const std::vector<Object*>& objects, RootType type) {
    if (locked_) return;

    auto start_time = std::chrono::high_resolution_clock::now();
    stats_.batch_operations++;

    for (Object* obj : objects) {
        if (obj && obj->is_valid_object()) {
            auto result = root_set_.insert(obj);
            if (result.second) {
                root_types_[obj] = type;
                update_stats(obj, type, true);
            } else {
                stats_.duplicate_removals++;
            }
        }
    }

    if (!objects.empty()) {
        list_dirty_ = true;
        auto end_time = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
        stats_.avg_add_time_us = duration.count() / static_cast<double>(objects.size());
    }
}

void GCRootSet::add_value_roots(const std::vector<Value>& values) {
    add_value_roots(values, RootType::USER);
}

void GCRootSet::add_value_roots(const std::vector<Value>& values, RootType type) {
    if (locked_) return;

    stats_.batch_operations++;
    for (const Value& value : values) {
        add_value_root(value, type);
    }
}

void GCRootSet::clear_roots() {
    if (locked_) return;

    root_set_.clear();
    root_types_.clear();
    root_list_.clear();
    list_dirty_ = false;

    std::lock_guard<std::mutex> lock(stats_mutex_);
    stats_ = Stats{};
}

void GCRootSet::clear_roots(RootType type) {
    if (locked_) return;

    std::vector<Object*> to_remove;
    for (const auto& pair : root_types_) {
        if (pair.second == type) {
            to_remove.push_back(pair.first);
        }
    }

    for (Object* obj : to_remove) {
        remove_root(obj);
    }
}

size_t GCRootSet::size() const {
    return root_set_.size();
}

size_t GCRootSet::unique_size() const {
    return root_set_.size(); // 由于使用set，所以都是唯一的
}

bool GCRootSet::contains(Object* obj) const {
    return root_set_.find(obj) != root_set_.end();
}

size_t GCRootSet::count_type(RootType type) const {
    size_t count = 0;
    for (const auto& pair : root_types_) {
        if (pair.second == type) {
            count++;
        }
    }
    return count;
}

const std::vector<Object*>& GCRootSet::get_roots() const {
    if (list_dirty_) {
        update_root_list();
    }
    return root_list_;
}

std::vector<Object*> GCRootSet::get_roots(RootType type) const {
    std::vector<Object*> result;
    for (const auto& pair : root_types_) {
        if (pair.second == type) {
            result.push_back(pair.first);
        }
    }
    return result;
}

GCRootSet::RootType GCRootSet::get_root_type(Object* obj) const {
    auto it = root_types_.find(obj);
    return (it != root_types_.end()) ? it->second : RootType::USER;
}

bool GCRootSet::set_root_type(Object* obj, RootType type) {
    if (!contains(obj)) {
        return false;
    }

    auto it = root_types_.find(obj);
    if (it != root_types_.end()) {
        RootType old_type = it->second;
        if (old_type != type) {
            update_stats(obj, old_type, false);
            it->second = type;
            update_stats(obj, type, true);
        }
        return true;
    }
    return false;
}

GCRootSet::Stats GCRootSet::get_stats() const {
    std::lock_guard<std::mutex> lock(stats_mutex_);
    Stats stats = stats_;
    stats.total_roots = root_set_.size();
    stats.unique_objects = root_set_.size();
    stats.stack_roots = count_type(RootType::STACK);
    stats.global_roots = count_type(RootType::GLOBAL);
    stats.register_roots = count_type(RootType::REGISTER);
    stats.internal_roots = count_type(RootType::INTERNAL);
    stats.user_roots = count_type(RootType::USER);
    return stats;
}

void GCRootSet::reset_stats() {
    std::lock_guard<std::mutex> lock(stats_mutex_);
    stats_ = Stats{};
}

void GCRootSet::lock() {
    if (!locked_) {
        locked_ = true;
    }
}

void GCRootSet::unlock() {
    locked_ = false;
}

void GCRootSet::print_stats() const {
    Stats stats = get_stats();
    std::cout << "=== GCRootSet 统计信息 ===" << std::endl;
    std::cout << "总根对象数: " << stats.total_roots << std::endl;
    std::cout << "唯一对象数: " << stats.unique_objects << std::endl;
    std::cout << "栈对象: " << stats.stack_roots << std::endl;
    std::cout << "全局对象: " << stats.global_roots << std::endl;
    std::cout << "寄存器对象: " << stats.register_roots << std::endl;
    std::cout << "内部对象: " << stats.internal_roots << std::endl;
    std::cout << "用户对象: " << stats.user_roots << std::endl;
    std::cout << "重复移除次数: " << stats.duplicate_removals << std::endl;
    std::cout << "批量操作次数: " << stats.batch_operations << std::endl;
    std::cout << "平均添加时间: " << stats.avg_add_time_us << "μs" << std::endl;
    std::cout << "========================" << std::endl;
}

void GCRootSet::validate_integrity() const {
    // 检查数据结构的一致性
    if (root_set_.size() != root_types_.size()) {
        std::cerr << "错误：root_set_ 和 root_types_ 大小不一致" << std::endl;
    }

    // 检查每个根对象都有类型信息
    for (Object* obj : root_set_) {
        if (root_types_.find(obj) == root_types_.end()) {
            std::cerr << "错误：根对象缺少类型信息" << std::endl;
        }
    }
}

// 私有辅助方法实现
void GCRootSet::update_root_list() const {
    root_list_.clear();
    root_list_.reserve(root_set_.size());

    for (Object* obj : root_set_) {
        root_list_.push_back(obj);
    }

    list_dirty_ = false;
}

void GCRootSet::update_stats(Object* obj, RootType type, bool added) {
    if (!obj) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);

    if (added) {
        stats_.total_roots++;

        // 按类型更新计数
        switch (type) {
            case RootType::STACK: stats_.stack_roots++; break;
            case RootType::GLOBAL: stats_.global_roots++; break;
            case RootType::REGISTER: stats_.register_roots++; break;
            case RootType::INTERNAL: stats_.internal_roots++; break;
            case RootType::USER: stats_.user_roots++; break;
        }
    } else {
        stats_.total_roots--;

        // 按类型更新计数
        switch (type) {
            case RootType::STACK: stats_.stack_roots--; break;
            case RootType::GLOBAL: stats_.global_roots--; break;
            case RootType::REGISTER: stats_.register_roots--; break;
            case RootType::INTERNAL: stats_.internal_roots--; break;
            case RootType::USER: stats_.user_roots--; break;
        }
    }
}

bool GCRootSet::extract_objects_from_value(const Value& value, std::vector<Object*>& objects) const {
    objects.clear();

    // 根据Value类型提取Object引用
    // 这里需要根据实际的Value类型系统来实现
    // 简化实现，只处理基本类型

    if (value.is_string()) {
        // 如果Value包含StringObject，提取它
        // TODO: 实现Value到Object的转换
    } else if (value.is_list()) {
        // 如果Value包含ListObject，提取它
        // TODO: 实现Value到Object的转换
    } else if (value.is_dict()) {
        // 如果Value包含DictObject，提取它
        // TODO: 实现Value到Object的转换
    }

    return !objects.empty();
}

// 增量垃圾回收实现
bool GarbageCollector::needs_incremental_collection() const {
    // 检查是否需要进行增量收集
    if (incremental_phase_ != IncrementalPhase::IDLE) {
        return true; // 已在收集中
    }

    // 简单触发策略：年轻代对象数量超过阈值
    const size_t young_gen_threshold = 1024;
    const auto& young_gen = generation_objects_[static_cast<size_t>(Generation::YOUNG)];
    return young_gen.size() > young_gen_threshold;
}

void GarbageCollector::start_incremental_collection() {
    if (incremental_phase_ != IncrementalPhase::IDLE) {
        return;
    }

    std::cout << "启动增量垃圾回收..." << std::endl;
    incremental_phase_ = IncrementalPhase::MARK_ROOTS;
    current_mark_index_ = 0;
    current_sweep_index_ = 0;
    mark_worklist_.clear();
    sweep_candidates_.clear();

    // 清除所有标记
    for (size_t i = 0; i < GENERATION_COUNT; ++i) {
        for (auto& obj : generation_objects_[i]) {
            if (obj) {
                obj->unmark();
            }
        }
    }
}

GarbageCollector::CollectionResult GarbageCollector::incremental_collect() {
    std::lock_guard<std::mutex> lock(gc_mutex_);

    if (!is_enabled_) {
        return CollectionResult{};
    }

    // 如果没有在收集状态，检查是否需要开始
    if (incremental_phase_ == IncrementalPhase::IDLE) {
        if (!needs_incremental_collection()) {
            return CollectionResult{}; // 不需要收集
        }
        start_incremental_collection();
    }

    auto start_time = std::chrono::high_resolution_clock::now();
    CollectionResult result = incremental_step();
    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);

    result.collection_time_ms = duration.count() / 1000.0;

    // 更新统计
    if (incremental_phase_ == IncrementalPhase::FINALIZE) {
        incremental_collections_++;
        finalize_incremental_collection();
    }

    incremental_time_ms_ += result.collection_time_ms;

    return result;
}

GarbageCollector::CollectionResult GarbageCollector::incremental_step() {
    CollectionResult result;
    auto start_time = std::chrono::high_resolution_clock::now();

    switch (incremental_phase_) {
        case IncrementalPhase::MARK_ROOTS:
            incremental_mark_roots_phase();
            break;
        case IncrementalPhase::MARK_WORKLIST:
            incremental_mark_worklist_phase();
            break;
        case IncrementalPhase::SWEEP_PREPARE:
            incremental_sweep_prepare_phase();
            break;
        case IncrementalPhase::SWEEP_OBJECTS:
            incremental_sweep_objects_phase();
            break;
        case IncrementalPhase::FINALIZE:
            finalize_incremental_collection();
            result.objects_collected = collection_count_;
            result.bytes_collected = result.objects_collected * estimate_average_object_size();
            break;
        case IncrementalPhase::IDLE:
            // 不应该到达这里
            break;
    }

    return result;
}

void GarbageCollector::incremental_mark_roots_phase() {
    if (!root_set_) {
        incremental_phase_ = IncrementalPhase::SWEEP_PREPARE;
        return;
    }

    size_t processed = 0;
    auto roots = root_set_->get_roots();

    // 处理一批根对象
    for (; current_mark_index_ < roots.size() && processed < INCREMENTAL_WORK_QUANTUM;
         ++current_mark_index_, ++processed) {
        Object* root = roots[current_mark_index_];
        if (root) {
            mark_object(root);
            push_to_mark_worklist(root);
        }
    }

    incremental_marked_objects_ += processed;

    // 检查是否完成根标记
    if (current_mark_index_ >= roots.size()) {
        std::cout << "增量标记根阶段完成，处理了 " << processed << " 个根对象" << std::endl;
        incremental_phase_ = IncrementalPhase::MARK_WORKLIST;
        current_mark_index_ = 0;
    }
}

void GarbageCollector::incremental_mark_worklist_phase() {
    size_t processed = 0;

    // 处理工作列表中的对象
    for (; current_mark_index_ < mark_worklist_.size() && processed < INCREMENTAL_WORK_QUANTUM;
         ++current_mark_index_, ++processed) {
        Object* obj = mark_worklist_[current_mark_index_];
        if (obj && obj->is_marked()) {
            // 标记该对象引用的其他对象
            if (obj->is_list()) {
                auto list_obj = static_cast<ListObject*>(obj);
                for (size_t i = 0; i < list_obj->size(); ++i) {
                    Value element = list_obj->get(i);
                    mark_value(element);
                }
            } else if (obj->is_dict()) {
                // TODO: 实现字典对象的标记
            }
        }
    }

    incremental_marked_objects_ += processed;

    // 检查是否完成工作列表处理
    if (current_mark_index_ >= mark_worklist_.size()) {
        std::cout << "增量标记工作列表阶段完成，处理了 " << processed << " 个对象" << std::endl;
        incremental_phase_ = IncrementalPhase::SWEEP_PREPARE;
        current_sweep_index_ = 0;
    }
}

void GarbageCollector::incremental_sweep_prepare_phase() {
    // 收集未标记的对象到清除候选列表
    for (size_t gen = 0; gen < GENERATION_COUNT; ++gen) {
        for (Object* obj : generation_objects_[gen]) {
            if (obj && !obj->is_marked() && !obj->is_forwarded()) {
                sweep_candidates_.push_back(obj);
            }
        }
    }

    std::cout << "增量清除准备阶段完成，找到 " << sweep_candidates_.size() << " 个候选对象" << std::endl;
    incremental_phase_ = IncrementalPhase::SWEEP_OBJECTS;
    current_sweep_index_ = 0;
}

void GarbageCollector::incremental_sweep_objects_phase() {
    size_t processed = 0;
    size_t collected = 0;

    // 处理一批待清除对象
    for (; current_sweep_index_ < sweep_candidates_.size() && processed < INCREMENTAL_WORK_QUANTUM;
         ++current_sweep_index_, ++processed) {
        Object* obj = sweep_candidates_[current_sweep_index_];
        if (obj && !obj->is_marked()) {
            finalize_object(obj);
            collected++;
            collection_count_++;
        }
    }

    incremental_swept_objects_ += processed;

    // 检查是否完成清除
    if (current_sweep_index_ >= sweep_candidates_.size()) {
        std::cout << "增量清除阶段完成，回收了 " << collected << " 个对象" << std::endl;
        incremental_phase_ = IncrementalPhase::FINALIZE;
    }
}

void GarbageCollector::finalize_incremental_collection() {
    std::cout << "增量垃圾回收完成" << std::endl;
    std::cout << "  标记对象数: " << incremental_marked_objects_ << std::endl;
    std::cout << "  清除对象数: " << incremental_swept_objects_ << std::endl;
    std::cout << "  总耗时: " << incremental_time_ms_ << "ms" << std::endl;

    // 重置状态
    incremental_phase_ = IncrementalPhase::IDLE;
    mark_worklist_.clear();
    sweep_candidates_.clear();
    current_mark_index_ = 0;
    current_sweep_index_ = 0;

    // 更新统计
    total_collections_++;
    total_collection_time_ms_ += incremental_time_ms_;

    // 重置增量统计
    incremental_marked_objects_ = 0;
    incremental_swept_objects_ = 0;
    incremental_time_ms_ = 0.0;

    print_generation_stats();
}

void GarbageCollector::push_to_mark_worklist(Object* obj) {
    if (obj && std::find(mark_worklist_.begin(), mark_worklist_.end(), obj) == mark_worklist_.end()) {
        mark_worklist_.push_back(obj);
    }
}

bool GarbageCollector::should_continue_incremental_step(const std::chrono::high_resolution_clock::time_point& start_time) const {
    auto now = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(now - start_time);
    return (duration.count() / 1000.0) < MAX_INCREMENTAL_TIME_MS;
}

void GarbageCollector::perform_promotions() {
    std::cout << "对象晋升阶段..." << std::endl;

    // 简单的晋升逻辑：将年轻代中存活的对象提升到老年代
    auto& young_gen = generation_objects_[static_cast<size_t>(Generation::YOUNG)];
    std::vector<Object*> to_promote;

    // 查找需要晋升的对象（已标记且在年轻代）
    for (Object* obj : young_gen) {
        if (obj && obj->is_marked()) {
            to_promote.push_back(obj);
        }
    }

    // 执行晋升
    for (Object* obj : to_promote) {
        // 简单晋升到OLD_0
        promote_object(obj, Generation::OLD_0);
        std::cout << "  对象 " << obj << " 从年轻代提升到老年代0" << std::endl;
    }

    std::cout << "晋升阶段完成，提升了 " << to_promote.size() << " 个对象" << std::endl;
}

} // namespace viml